﻿namespace sfcms.api
{
    using System;
    using System.Data;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.IO;
    using System.Web;

    public class file : child
    {
        private byte[] _data;
        private byte[] _thumbnaildata;
        public string contenttype;
        public string fileextension;
        public string filename;
        public int size;
        public const int THUMBNAIL_SIZE = 0x30;

        public static file[] byparentid(long parentid)
        {
            DataTable dt = new database().ExecuteDataTable("SELECT F.ID, F.ContentType, F.FileName, F.FileExtension, DATALENGTH(F.Data) AS Size FROM SFCMS_FilePath FP (NOLOCK) JOIN SFCMS_File F (NOLOCK) ON FP.FileID = F.[ID] WHERE FP.[ParentID] = @0 ORDER BY F.[FileName]", new object[] { "@0", parentid });
            file[] files = new file[dt.Rows.Count];
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                files[i] = new file { id = Convert.ToInt64(dt.Rows[i]["ID"]), contenttype = dt.Rows[i]["ContentType"].ToString(), filename = dt.Rows[i]["FileName"].ToString(), fileextension = dt.Rows[i]["FileExtension"].ToString(), size = Convert.ToInt32(dt.Rows[i]["Size"]) };
            }
            return files;
        }

        public void delete()
        {
            new database().ExecuteNonQuery("DELETE SFCMS_File WHERE [ID] = @0", new object[] { "@0", base.id });
        }

        public static file fromid(long id)
        {
            DataTable dt = new database().ExecuteDataTable("SELECT [ID], FileName, FileExtension, ContentType, DATALENGTH(Data) as Size FROM SFCMS_File (NOLOCK) WHERE [ID] = @0", new object[] { "@0", id });
            if (dt.Rows.Count == 0)
            {
                return null;
            }
            return new file { id = id, contenttype = dt.Rows[0]["ContentType"].ToString(), filename = dt.Rows[0]["FileName"].ToString(), fileextension = dt.Rows[0]["FileExtension"].ToString(), size = Convert.ToInt32(dt.Rows[0]["Size"]) };
        }

        public static file fromupload(HttpPostedFile postedfile)
        {
            file newFile = new file();
            setfile(newFile, postedfile);
            newFile.id = Convert.ToInt64(new database().ExecuteScalar("INSERT INTO SFCMS_File (FileName, FileExtension, ContentType, Data) VALUES (@0, @1, @2, @3)\r\nSELECT SCOPE_IDENTITY()", new object[] { "@0", newFile.filename, "@1", newFile.fileextension, "@2", newFile.contenttype, "@3", newFile.data }));
            return newFile;
        }

        private static void setfile(file filetoset, HttpPostedFile file)
        {
            filetoset.filename = Path.GetFileNameWithoutExtension(file.FileName);
            filetoset.fileextension = Path.GetExtension(file.FileName).TrimStart(new char[] { '.' });
            filetoset.contenttype = file.ContentType;
            filetoset.size = file.ContentLength;
            filetoset._data = new byte[file.ContentLength];
            file.InputStream.Read(filetoset._data, 0, file.ContentLength);
        }

        public void update(HttpPostedFile postedFile)
        {
            setfile(this, postedFile);
            new database().ExecuteNonQuery("UPDATE SFCMS_File SET FileName = @0, FileExtension = @1, ContentType = @2, Data = @3 WHERE [ID] = @4", new object[] { "@0", this.filename, "@1", this.fileextension, "@2", this.contenttype, "@3", this.data, "@4", base.id });
        }

        public byte[] data
        {
            get
            {
                if (this._data == null)
                {
                    this._data = (byte[]) new database().ExecuteScalar("SELECT Data FROM SFCMS_File (NOLOCK) WHERE [ID] = @0", new object[] { "@0", base.id });
                }
                return this._data;
            }
        }

        public bool isimage
        {
            get
            {
                if (this.fileextension == null)
                {
                    return false;
                }
                return "tiff jpg jpeg gif png bmp".Contains(this.fileextension.ToLowerInvariant());
            }
        }

        public byte[] thumbnaildata
        {
            get
            {
                if (base.id == 0L)
                {
                    throw new InvalidOperationException("The file must be saved first");
                }
                if (!this.isimage)
                {
                    return this.data;
                }
                if (this._thumbnaildata == null)
                {
                    double thRate;
                    Image th = Image.FromStream(new MemoryStream(this.data));
                    if ((th.Width <= 0x30) && (th.Height <= 0x30))
                    {
                        return (this._thumbnaildata = this.data);
                    }
                    MemoryStream thStream = new MemoryStream();
                    if (th.Width > 0x30)
                    {
                        thRate = 48.0 / ((double) th.Width);
                    }
                    else
                    {
                        thRate = 48.0 / ((double) th.Height);
                    }
                    int thWidth = Convert.ToInt32((double) (th.Width * thRate));
                    int thHeight = Convert.ToInt32((double) (th.Height * thRate));
                    th.GetThumbnailImage(thWidth, thHeight, null, IntPtr.Zero).Save(thStream, ImageFormat.Jpeg);
                    this._thumbnaildata = thStream.ToArray();
                }
                return this._thumbnaildata;
            }
        }
    }
}

